package com.xiaozhen.tcp.zookeeper;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @Author: zhenweisheng
 * @Date: 2020/7/31 13:51
 */
public class ServiceDiscovery {

    private static final Logger logger = LoggerFactory.getLogger(ServiceDiscovery.class);

    private CountDownLatch latch = new CountDownLatch(1);

    private volatile List<String> serviceAddressList = new ArrayList<>();

    /**
     * 注册中心的地址
     */
    private String registryAddress;

    public ServiceDiscovery(String registryAddress) {
        this.registryAddress = registryAddress;

        ZooKeeper zk = connectServer();
        if (zk != null) {
            watchNode(zk);
        }
    }

    /**
     * 通过服务发现，获取服务提供方的地址
     *
     * @return
     */
    public String discover() {
        String data = null;
        int size = serviceAddressList.size();
        if (size > 0) {
            //只有一个服务提供方
            if (size == 1) {
                data = serviceAddressList.get(0);
                logger.info("unique service address : {}", data);
            } else {          //使用随机分配法。简单的负载均衡法
                data = serviceAddressList.get(ThreadLocalRandom.current().nextInt(size));
                logger.info("choose an address : {}", data);
            }
        }
        return data;
    }

    /**
     * 连接 zookeeper
     *
     * @return
     */
    private ZooKeeper connectServer() {

        ZooKeeper zk = null;
        try {
            zk = new ZooKeeper(registryAddress, 2000, new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    if (event.getState() == Watcher.Event.KeeperState.SyncConnected) {
                        latch.countDown();
                    }
                }
            });
            latch.await();
        } catch (IOException | InterruptedException e) {
            logger.error("", e);
        }
        return zk;
    }

    /**
     * 获取服务地址列表
     *
     * @param zk
     */
    private void watchNode(final ZooKeeper zk) {
        try {
            //获取子节点列表
            List<String> nodeList = zk.getChildren("/route", new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    if (event.getType() == Event.EventType.NodeChildrenChanged) {
                        //发生子节点变化时再次调用此方法更新服务地址
                        watchNode(zk);
                    }
                }
            });
            logger.info("node data: {}", nodeList);
            this.serviceAddressList = nodeList;
        } catch (KeeperException | InterruptedException e) {
            logger.error("", e);
        }
    }
}
